<script setup lang="ts">
import { legacyLogicalPropertiesTransformer } from 'ant-design-vue';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { db } from './utils/DexieDB';
import { useIntervalFn } from '@vueuse/core';
import { isAndroid } from './utils/UtilFun';
import { getVersionApi, queryWhitelistInfoApi, sendDeviceBaseInfoApi } from './API/API';
import { useRouter } from 'vue-router';
import { post, upload } from './utils/Fetch';
import pkg from '../package.json';

const router = useRouter()

// 初始化设备对象
const device = ref<device>({
  used: 0,
  disinfectAutoMode: true,
  disinfectTime: 1,
  allNum: 100,
  tell: '如有疑问，请联系护士站',
  supportTell: '11111111111',
  volume: 0,
  maxSaveTime: 240,
  maxVacantNum: 5,
  maxWaitCloseTime: 1,

  // baseUrl: 'http://192.168.31.15:8080/closet',
  IntervalTaskIsRunning: false,
  baseUrl: 'http://219.145.17.226:7856/closet',
  timeout: 1 / 12,
  backViewTimeOut: 0.25,

  serial: '',
  board: '',
  devicename: '',
  support: '',
  area: '',
  department: '',
  illArea: '',
  videoUrl: '',
  versionUrl: '',
  version: pkg.version
})
// async function openDB() {
//   await db.open();
// }
// openDB();

const settings = reactive({
  // 默认色板
  colorPrimary: '#3b4ae1',
  // 警告色
  colorWarning: '#fa541c',
  // 错误色
  colorError: '#f5222d',
  // 背景色
  colorBgContainer: '#fff',
  // 文字色
  colorTextBase: '#000',
  // 圆角
  borderRadius: 4,
  // 边框色
})



// 设备初始化
async function deviceInit() {
  if (isAndroid()) {
    window.ClosetAndroid.sendLog("Vue 应用初始化完成");
    const volumn = window.ClosetAndroid.getMediaVolume()
    const serial = window.ClosetAndroid.getDeviceSerialNumber()
    device.value.volume = volumn
    device.value.serial = serial
  }

  const deviceExists = await db.device.count();
  if (deviceExists === 0) {
    try {
      await db.device.add({ ...device.value });
      console.log('设备数据初始化完成');
    } catch (error) {
      console.error('设备数据初始化失败:', error);
    }
  } else {
    const deviceInstance = await db.device.get(1) as device;
    const allNum = deviceInstance.allNum
    const used = await db.testTube.count()

    device.value.allNum = allNum
    device.value.used = used

    console.log('设备数据初始化完成');
  }
}


// 发送基本信息
async function sendBaseDeviceInfo() {
  sendDeviceBaseInfoApi({
    area: device.value.area,
    serial: device.value.serial,
    board: device.value.board,
    devicename: device.value.devicename,
    tubeUse: device.value.used,
    tubeAll: device.value.allNum,
    tubeRemain: device.value.allNum - device.value.used,
  }).then(async ({ code, data }) => {
    console.log('发送基本信息成功:', data);
    // 更改设备信息
    device.value.allNum = data.device.tubeAll
    device.value.area = data.device.area
    device.value.board = data.device.board
    device.value.department = data.device.department
    device.value.illArea = data.device.illArea
    device.value.devicename = data.device.deviceName
    device.value.support = data.device.principal
    device.value.supportTell = data.device.tell
    device.value.versionUrl = data.device.versionUrl

    await db.device.update(1, { ...device.value })
    // 更新医护
    if (data.nurse.length > 0) {
      const count = await db.nurse.count();
      if (count > 0) {
        await db.nurse.clear();
      }
      // 处理 id 为 null 的数据
      const nursesToAdd = data.nurse.map((nurse: nurse) => {
        if (nurse.id === null) {
          const { id, ...rest } = nurse;
          return rest;
        }
        return nurse;
      });
      db.nurse.bulkAdd(nursesToAdd).catch(err => {
        console.error('批量添加护士数据失败:', err);
      });
    }
    // 更新白名单
    if (data.whites.length > 0) {
      const count = await db.whites.count();
      if (count > 0) {
        await db.whites.clear();
      }

      // 处理 id 为 null 的数据
      const nursesToAdd = data.whites.map((white: white) => {
        if (white.id === null) {
          // 移除 null 的 id 字段，让 Dexie 自动生成
          const { id, ...rest } = white;
          return rest;
        }
        return white;
      });
      db.whites.bulkAdd(nursesToAdd).catch(err => {
        console.error('批量添加白名单数据失败:', err);
      });
    }
  }).catch(err => {
    console.log('发送基本信息失败:', err);
  })
}
// 查询白名单信息下的可存放试管信息
async function getWhiteListInfo() {
  queryWhitelistInfoApi({
    serial: device.value.serial,
  }).then(async ({ code, data }) => {
    console.log('查询白名单info信息成功:', data);
    // 更新白名单信息下的info信息
    db.info.bulkAdd(data).catch(err => {
      console.error('批量添加白名单信息下的可存放试管信息数据失败:', err);
    });
  }).catch(err => {
    console.log('查询白名单info信息失败:', err);
  })
}

// 重试机制
async function reTryTasks() {
  const tasks = await db.retryTasks.limit(10).toArray();

  if (tasks.length === 0) {
    console.log('没有重试任务');
    return;
  }

  for (const task of tasks) {
    console.log('重试任务开始执行:', task);
    const url = task.url;
    new Promise((resolve, reject) => {
      if (url === '/addPut2' || url === '/addOut2') {
        // 处理文件上传的重试
        console.log('data', task.info);
        console.log('file', task.file);
        // const serializedFormData = JSON.parse(task.info);
        // for (const key in serializedFormData) {
        //   if (key !== 'file') {
        //     data[key] = serializedFormData[key];
        //   }
        // }
        console.log({ ...task.info, file: task.file });

        upload(url, { ...task.info, file: task.file }).then(({ code }) => {
          if (code == 200) {
            resolve(true)
          } else {
            reject(false)
          }
        }).catch(() => {
          reject(false)
        })
      } else {
        post(task.url, JSON.parse(task.info.body)).then(({ code }) => {
          if (code == 200) {
            resolve(true)
          } else {
            reject(false)
          }
        }).catch(() => { reject(false) })
      }
    }).then((res) => {
      if (res) {
        console.log('重试任务发送成功:', task);
        db.retryTasks.delete(task.id).then(() => {
          console.log('重试任务删除成功:', task);
        }).catch((err) => {
          console.error('重试任务删除失败:', err);
        });
      } else {
        console.log('重试任务发送失败，等待下一次重试:', task);
      }
    })
  }
}


// 20分钟所有定时任务
async function sendIntervalTasks() {
  console.log('sendIntervalTasks 函数被调用 20分钟定时任务开始执行');
  useIntervalFn(
    async () => {
      try {
        //20分钟发送设备基本信息
        await sendBaseDeviceInfo();
      } catch (error) {
        console.error('定时任务执行失败:', error);
      }
    },
    1200000, // 20分钟
    {
      immediate: true, // 立即执行一次
      immediateCallback: true
    }
  );

  useIntervalFn(
    async () => {
      try {
        //18分钟查询白名单信息下的可存放试管信息
        await getWhiteListInfo();
      } catch (error) {
        console.error('定时任务执行失败:', error);
      }
    },
    1080000, // 18分钟
    {
      immediate: true, // 立即执行一次
      immediateCallback: true
    }
  );

  useIntervalFn(
    async () => {
      try {
        //18分钟查询白名单信息下的可存放试管信息
        await reTryTasks();
      } catch (error) {
        console.error('定时任务执行失败:', error);
      }
    },
    // 1080000, // 18分钟
    1200000,
    {
      immediate: true, // 立即执行一次
      immediateCallback: true
    }
  );

  useIntervalFn(
    async () => {
      try {
        const now = new Date();
        const hours = now.getHours();

        if (hours === 0) {
          // 保留4天info 跟30天testTubeHistory  计算4天前的时间戳
          const fourDaysAgo = new Date(now.getTime() - 4 * 24 * 60 * 60 * 1000);
          // 计算30天前的时间戳
          const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          await db.info.where('eventTime').below(fourDaysAgo).delete();
          console.log('已清理过期的info数据');
          // 删除testTubeHistory表中30天前的数据
          await db.testTubeHistory.where('outTime').below(thirtyDaysAgo).delete();
          console.log('已清理过期的testTubeHistory数据');

          window.ClosetAndroid.deletePhoto()
          console.log('已清理过期的照片文件');
        }

        if (hours === 2) {
          // 执行定时任务
          // executeScheduledTasks();
          // 重启屏
        }
        if (hours === 3) {
          // 执行定时任务
          // executeScheduledTasks();
          // 查询更新
          getVersionApi({
            serial: device.value.serial
          }).then(res => {

          })
        }


      } catch (error) {
        console.error('定时任务执行失败:', error);
      }
    },
    // 1080000, // 18分钟
    60000,
    {
      immediate: true, // 立即执行一次
      immediateCallback: true
    }
  );
  // }

}


// 每秒获取轨道位置
async function sendReadTrackLocation() {
  if (isAndroid()) {
    useIntervalFn(
      async () => {
        try {
          console.log('读取轨道锁状态');
          window.ClosetAndroid.readTrackLock()
        } catch (error) {
          console.error('定时任务执行失败:', error);
        }
      },
      1000, // 1秒
      {
        immediate: true, // 立即执行一次
        immediateCallback: true
      }
    );
  }
}


// 获取轨道位置
function getTrackLocation(hexString: string) {
  console.log('获取到的轨道位置信息字符串', hexString);

  if (hexString == "010402000178F0") {
    // 物理按钮长按关闭，发送关闭
    // window.ClosetAndroid.closeTrackLock();
    window.ClosetAndroid.closeTrack();
  } else if (hexString == '55FEFE0110000000000000000000000000000000006A14') {
    // 已经完全关闭
  } else {
    return
  }
}

onMounted(async () => {
  console.log('APP onMounted', new Date().toLocaleString());


  const deviceInstance = await db.device.get(1) as device;
  const TaskIsRunning = deviceInstance?.IntervalTaskIsRunning || false;

  console.log('运行定时任务', deviceInstance?.IntervalTaskIsRunning, TaskIsRunning);

  if (!TaskIsRunning) {
    console.log('APP onMounted 启动定时任务');
    deviceInit().then(() => {
      sendIntervalTasks()
      sendReadTrackLocation()
    })
  }

  db.on('close', () => {
    console.log('数据库已关闭');
    // router.push('/Home').then(() => {
    //   router.go(0)
    // })
  })

  // db.open().then(() => {
  //   console.log('数据库已打开');

  // })


  window.getTrackLocationFn = getTrackLocation
})

onUnmounted(() => {
  console.log('APP onUnmounted');
  // db.close()
})

</script>

<template>
  <a-config-provider :theme="{ token: settings }" :locale="zhCN" :transformers="[legacyLogicalPropertiesTransformer]">
    <a-style-provider hash-priority="high">
      <router-view></router-view>
    </a-style-provider>
  </a-config-provider>
</template>

<style lang="scss">
@font-face {
  font-family: 'textTTF';
  src: url('@/assets/font/text.ttf');
}

#app {
  .ant-page-header {
    position: sticky;
    top: 0;
    z-index: 1;
    background-color: #fff;
    width: 100%;
  }

  .ant-page-header .ant-page-header-back {
    font-size: .4rem;
  }

  .ant-page-header-heading-title {
    font-size: .5rem;
    line-height: .6rem;
  }

  .ant-table .ant-table-header tr th {
    font-size: .3rem !important;
  }

  .ant-table-tbody>tr>td {
    font-size: .25rem;
  }

  // .ant-table-thead>tr>th,
  // .ant-table-tbody>tr>td {
  // padding: .2rem .1rem !important;
  // }

  // :deep(.ant-table-tbody>tr>td) {
  //   font-size: .25rem;
  // }

  // :deep(.ant-table .ant-table-thead>tr>th) {
  //   font-size: .3rem !important;
  // }

  // :deep(.ant-table-thead>tr>th),
  // :deep(.ant-table-tbody>tr>td) {
  //   padding: .2rem .1rem !important;
  // }

  :deep(.ant-btn) {
    font-size: .325rem;
    height: auto;
    padding: .125rem .375rem;
  }
}
</style>
